package com.hmdp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisCommand;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 小旭
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CacheClient cacheClient;

    /**
     * 根据id查询店铺
     * @param id
     * @return
     */
    @Override
    public Shop queryByIds(Long id) {
        //解决缓存穿透问题
        //return queryWithPassThrough(id);
        //互斥锁解决缓存击穿
        /* Result result = queryWithMutex(id);*/
        //逻辑过期解决缓存击穿
        /*Result result1 = queryWithLogicalExpire(id);*/
        //Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        Shop shop1 = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop1;
    }

    /**
     * 互斥锁解决缓存击穿
     * @param id
     * @return
     */
    private Result queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //1.根据id从redis中查询店铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.命中，有正常值，则从redis中返回该信息
        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        //2.1命中，但是为""值，返回404
        if ("".equals(shopJson)) {
            return Result.fail("店铺不存在");
        }
        //3.缓存重建
        String lockKey = "shop:lock:" + id;
        Shop shop = null;
        try {
            //3.1获取互斥锁
            boolean isLock = tryLock(lockKey);
            //3.1没有获取到，休眠一段时间，并重新去redis中查询
            if (!isLock) {
                Thread.sleep(50);
                Result result = queryWithMutex(id);
                return result;
            }
            //获取锁成功后，需要再去redis中查看缓存是否存在，做DoubleCheck
            //4.获取到了，去数据库中查询
            shop = this.getById(id);
            //5.不存在，返回404
            if (shop == null) {
                //将空值写入redis中
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                //返回错误信息
                return Result.fail("店铺不存在");
            }
            //6.存在，将该店铺信息写入redis中
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //7.释放互斥锁
            unLock(lockKey);
        }

        return Result.ok(shop);
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 逻辑过期解决缓存击穿
     * @param id
     * @return
     */
    private Result queryWithLogicalExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //1.根据id从redis中查询店铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否命中
        if (StrUtil.isBlank(shopJson)) {
            //3.未命中，直接返回不存在
            return Result.fail("商铺不存在");
        }
        //4.命中，需要把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data,Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //5.判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //5.1未过期，直接返回店铺信息
            return Result.ok(shop);
        }
        //5.2已过期，需要缓存重建
        //6.缓存重建
        //6.1获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        //6.2判断是否获取锁成功
        if (isLock) {
            //6.3成功，开启独立线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //重建缓存
                    this.saveSHop2Redis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
        }
        //6.4未成功，返回过期的店铺信息
        return Result.ok(shop);
    }

    /**
     * 缓存空对象+旁路策略解决缓存穿透
     * @param id
     * @return
     */
    private Result queryWithPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //1.根据id从redis中查询店铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.命中，有正常值，则从redis中返回该信息
        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        //2.1命中，但是是""值，返回404
        if ("".equals(shopJson)) {
            return Result.fail("店铺不存在");
        }
        //3.不存在，去数据库中查询
        Shop shop = this.getById(id);
        //4.不存在，返回404
        if (shop == null) {
            //将空值写入redis中
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            //返回错误信息
            return Result.fail("店铺不存在");
        }
        //5.存在，将该店铺信息写入redis中
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(shop);
    }

    /**
     * 先更新数据库，在删除缓存
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("id不能为空");
        }
        //1.先操作数据库
        this.updateById(shop);
        //2.再删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());

        return Result.ok();
    }

    /**
     * 根据类型查询店铺信息
     * 如果传输了xy经纬度，会根据位置排序
     * @param typeId
     * @param current
     * @param x
     * @param y
     * @return
     */
    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //判断是否需要根据坐标查询
        if (x == null || y == null) {
            //不需要，则按数据库查询
            Page<Shop> page = query().eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            //返回数据
            return Result.ok(page.getRecords());

        }
        //需要，按坐标查询
        //计算分页参数
        //每页5条：0~4、5~10
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        //查询redis，按照距离排序并分页,查询结果为shopId、distance
        String key = SHOP_GEO_KEY + typeId;

        //GeoResults中存着所有数据
        //GeoRadiusCommandArgs.newGeoSearchArgs()设置查询时携带参数，携带距离
        //其中limit只能设置结束范围，无法设置开始的范围，默认从头开始，因此无法实现传统的分页，只能自行设置逻辑分页
        //每次查询，只能查询到 0 ~ end 的部分
        GeoResults<RedisGeoCommands.GeoLocation<String>> results =  stringRedisTemplate.opsForGeo()
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoRadiusCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );

        //从上述查询结果中解析出店铺id
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }

        //获取到存着每条店铺的id和距离的list集合
        //默认距离是从小到大
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();

        if (list.size() <= from) {
            //没有下一页了，返回空集合
            return Result.ok(Collections.emptyList());
        }

        //截取 from ~ end 的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>();

        //通过stream流改变list集合，并循环将每个店铺id和distance相关联，添加到map集合中
        list.stream().skip(from).forEach(result -> {
            //获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            //获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });

        //根据id查询shop
        //此方法是根据 select * from shop where id in(**,**,**),返回结果是无序的
        //List<Shop> shops = this.listByIds(ids);
        //实现有序查询
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = this.query().in("id", ids).last("order by field(id," + idStr + ")").list();

        for (Shop shop : shops) {
            Distance distance = distanceMap.get(shop.getId());
            shop.setDistance(distance.getValue());
        }
        //返回
        //此时的shops集合就是距离从小到大有序的了，并携带距离
        return Result.ok(shops);

    }

    /**
     * 存入缓存的redis设置逻辑过期时间
     * @param id
     * @param expireSeconds
     */
    public void saveSHop2Redis(Long id, Long expireSeconds) {
        //1.查询店铺信息
        Shop shop = getById(id);
        //2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //3.永久写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 上锁
     * @param key
     * @return
     */
    private boolean tryLock(String key) {
        //缓存内容随便设置，过期时间设置为10秒
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 解锁
     * @param key
     * @return
     */
    private boolean unLock(String key) {
        //释放锁，将之前的key删除即可
        Boolean flag = stringRedisTemplate.delete(key);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 获取店铺ID列表
     * @return
     */
    @Override
    public List<Long> getShopIDLists(){
        List<Shop> list = this.list();
        List<Long> shopIDLists = list.stream().map(shop -> shop.getId()).collect(Collectors.toList());
        return shopIDLists;
    }

}
